import random
import string
from django.core.mail import send_mail
from django.conf import settings
from .redis_client import redis_client

def generate_verification_code(length=6):
    """生成验证码"""
    return ''.join(random.choices(string.digits, k=length))

def send_verification_email(email, code):
    """发送验证码邮件"""
    subject = 'Campus Nexus Registration Verification Code'
    message = f'''
    Hello,

    You are registering an account for the Campus Nexus. Your verification code is: {code}.

    The verification code is valid for 5 minutes, please use it promptly.

    If this was not your action, please disregard this email.

    — The Campus Nexus Team
    '''
    
    try:
        send_mail(
            subject=subject,
            message=message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[email],
            fail_silently=False,
        )
        return True
    except Exception as e:
        print(f"Send email failed: {e}")
        return False

def store_verification_code(email, code):
    """将验证码存储到Redis"""
    key = f"verification_code:{email}"
    redis_client.set(key, code, ex=settings.VERIFICATION_CODE_EXPIRE_TIME)

def verify_code(email, code):
    """验证验证码"""
    key = f"verification_code:{email}"
    stored_code = redis_client.get(key)
    
    if stored_code and stored_code == code:
        # 验证成功后删除验证码
        redis_client.delete(key)
        return True
    return False

def send_and_store_verification_code(email):
    code = generate_verification_code()

    store_verification_code(email, code)

    success = send_verification_email(email, code)
    
    return success, code if success else None

def send_registration_approval_email(email, nickname):
    """发送注册申请通过通知邮件"""
    subject = 'Campus Nexus Registration Application Approved'
    message = f'''
    Hello {nickname},

    Congratulations! Your registration application for Campus Nexus has been approved.

    You can now log in to the system using your registered email address and password.

    Welcome to Campus Nexus! We're excited to have you as part of our community.

    If you have any questions or need assistance, please don't hesitate to contact us.

    — The Campus Nexus Team
    '''
    
    try:
        send_mail(
            subject=subject,
            message=message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[email],
            fail_silently=False,
        )
        return True
    except Exception as e:
        print(f"Sending application via notification email failed: {e}")
        return False